<template>
  <ul class="list">
    <li class="item" v-for="item of letterArray" :key="item" @click="handleLetterClick"
        :ref="item"
        @touchstart.prevent="handleTouchStart"
        @touchmove="handleTouchMove"
        @touchend="handleTouchEnd">
      {{item}}
    </li>
  </ul>

</template>

<script>
  export default {
    name: 'CityAlphablet',
    props: {
      cities: Object
    },
    data: function () {
      return {
        touchStatus: false,
        startY: 0,
        timer: null
      }
    },
    /**
     * 当数据更新的时候会去执行该方法
     */
    updated: function () {
      this.startY = this.$refs['A'][0].offsetTop
    },
    computed: {
      letterArray: function () {
        const letters = []
        for (let i in this.cities) {
          letters.push(i)
        }
        return letters
      }
    },
    methods: {
      handleLetterClick: function (e) {
        this.$emit('letterChange', e.target.innerText)
      },
      handleTouchStart: function (e) {
        this.touchStatus = true
      },
      handleTouchMove: function (e) {
        if (this.touchStatus) {
          if (this.timer) {
            clearTimeout(this.timer)
          }
          this.timer = setTimeout(() => {
            /**
             * 获取A距离顶部的距离
             * @type {number}
             */
            // const startY =
            /**
             *手指触摸距离顶部的距离
             */
            const touchY = e.touches[0].clientY - 79
            /**
             * 触摸第几个
             */
            const index = Math.floor((touchY - this.startY) / 20)
            if (index >= 0 && index < this.letterArray.length) {
              this.$emit('letterChange', this.letterArray[index])
            }
          }, 16)
        }
      },
      handleTouchEnd: function (e) {
        this.touchStatus = false
      }
    }
  }
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .list {
    display flex
    flex-direction column
    justify-content center
    position: absolute
    top: 1.58rem;
    right: 0;
    bottom: 0;
    width: .4rem;
  }

  .item {
    text-align center;
    line-height .4rem;
    color $bgColor
  }
</style>
